# ====================== Python原生应用部分 ======================
try:
    import pyi_splash

    pyi_splash.close()  # 关闭PyInstaller启动画面（如果存在）
except ImportError:
    pass

import sys
import json
import os
import struct


def read_message():
    """
    读取来自浏览器的消息
    消息格式：4字节长度头 + JSON内容
    """
    raw_length = sys.stdin.buffer.read(4)
    if not raw_length:
        return None
    # 解包消息长度（使用本机字节序）
    message_length = struct.unpack('@I', raw_length)[0]
    # 读取实际消息内容
    message = sys.stdin.buffer.read(message_length).decode('utf-8')
    return json.loads(message)


def send_message(message):
    """
    发送响应消息到浏览器
    """
    encoded_message = json.dumps(message).encode('utf-8')
    # 先发送4字节长度头
    sys.stdout.buffer.write(struct.pack('@I', len(encoded_message)))
    # 发送实际JSON数据
    sys.stdout.buffer.write(encoded_message)
    sys.stdout.buffer.flush()


def handle_write_operation(file_path, content):
    """
    处理文件写入操作
    """
    try:
        # 检查是否包含路径遍历攻击（安全措施）
        if '../' in file_path or '..\\' in file_path:
            return {"status": "error", "reason": "非法文件路径"}

        # 自动创建目录（如果不存在）
        os.makedirs(os.path.dirname(file_path), exist_ok=True)

        # 使用with语句确保文件正确关闭
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)

        return {"status": "success", "message": f"文件已成功写入 {file_path}"}

    except PermissionError:
        return {"status": "error", "reason": "文件写入权限被拒绝"}
    except OSError as e:
        return {"status": "error", "reason": f"系统错误: {file_path}"}
    except Exception as e:
        return {"status": "error", "reason": f"未知错误: {str(e)}"}


def handle_read_operation(file_path):
    """
    处理文件读取操作
    """
    try:
        # 检查文件是否存在
        if not os.path.exists(file_path):
            return {"status": "error", "reason": "文件不存在"}

        # 检查是否是文件（防止目录遍历）
        if not os.path.isfile(file_path):
            return {"status": "error", "reason": "路径不是文件"}

        # 读取文件内容
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()

        return {"status": "success", "content": content}

    except UnicodeDecodeError:
        return {"status": "error", "reason": "非UTF-8编码文件"}
    except PermissionError:
        return {"status": "error", "reason": "文件读取权限被拒绝"}
    except Exception as e:
        return {"status": "error", "reason": f"读取失败: {str(e)}"}


# 主消息循环
while True:
    message = read_message()
    if message is None:
        break

    # 获取操作参数
    operation = message.get('action')
    file_path = message.get('filePath')

    # 参数检查
    if not operation or not file_path:
        send_message({"status": "error", "reason": "缺少必要参数"})
        continue

    # 操作路由
    if operation == "write":
        # 写入操作需要内容参数
        content = message.get('content')
        if content is None:
            send_message({"status": "error", "reason": "缺少写入内容"})
            continue
        response = handle_write_operation(file_path, content)
    elif operation == "read":
        response = handle_read_operation(file_path)
    else:
        response = {"status": "error", "reason": "未知操作类型"}

    send_message(response)